package com.cxh.mediasessiondemo;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.browse.MediaBrowser;
import android.media.session.MediaController;
import android.os.Bundle;
import android.widget.RemoteViews;

import java.util.Locale;

/**
 * Created by Cxh
 * Time : 2021/10/23  00:53
 * Desc :
 */
public class NotificationHelper implements IMediaData {

    private static final String CHANNEL_ID = "channel_id";
    private static final String CHANNEL_NAME = "MediaSessionDemo";

    private static final String ACTION_PRE = "com.cxh.mediasessiondemo.action.pre";
    private static final String ACTION_PLAY = "com.cxh.mediasessiondemo.action.play";
    private static final String ACTION_NEXT = "com.cxh.mediasessiondemo.action.next";
    private static final String ACTION_TYPE = "com.cxh.mediasessiondemo.action.type";

    private static final int NOTIFICATION_ID = 1;

    private MusicPlayerService mPlayerService;
    private Notification mNotification;
    private NotificationManager mNotificationManager;
    private RemoteViews mRemoteViews;
    private MediaController mMediaController;

    public NotificationHelper(MusicPlayerService context, MediaController mediaController) {
        mPlayerService = context;
        mMediaController = mediaController;
        mRemoteViews = new RemoteViews(mPlayerService.getPackageName(), R.layout.view_notification);

        // 点击事件
        registerViewClick(R.id.btn_pre, ACTION_PRE);
        registerViewClick(R.id.btn_play, ACTION_PLAY);
        registerViewClick(R.id.btn_next, ACTION_NEXT);
        registerViewClick(R.id.tv_loop_state, ACTION_TYPE);

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_PRE);
        intentFilter.addAction(ACTION_PLAY);
        intentFilter.addAction(ACTION_NEXT);
        intentFilter.addAction(ACTION_TYPE);
        mPlayerService.registerReceiver(mBroadcastReceiver, intentFilter);
    }

    public void requestNotification() {
        NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
                NotificationManager.IMPORTANCE_HIGH);
        mNotificationManager = mPlayerService.getSystemService(NotificationManager.class);
        mNotificationManager.createNotificationChannel(notificationChannel);

        mNotification = new Notification.Builder(mPlayerService, CHANNEL_ID)
                .setCustomBigContentView(mRemoteViews)
                .setCustomContentView(mRemoteViews)
                .setGroupSummary(false)
                .setPriority(Notification.PRIORITY_HIGH)
                .setChannelId(CHANNEL_ID)
                .setOngoing(true)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .build();
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

    public void cancel() {
        NotificationManager notificationManager = mPlayerService.getSystemService(NotificationManager.class);
        notificationManager.cancel(NOTIFICATION_ID);
        notificationManager.deleteNotificationChannel(CHANNEL_ID);

        mPlayerService.unregisterReceiver(mBroadcastReceiver);
        mPlayerService = null;
    }

    public void updateMediaItem(MediaBrowser.MediaItem mediaItem, int max, int progress, int loopType,
                                boolean isPlaying) {
        if (null == mediaItem) {
            return;
        }

        mRemoteViews.setTextViewText(R.id.tv_music_title, mediaItem.getDescription().getTitle());
        mRemoteViews.setTextViewText(R.id.tv_progress, String.format(Locale.CHINA, "%1$ds", (max - progress) / 1000));
        mRemoteViews.setTextViewText(R.id.tv_loop_state, getLoopText(loopType));
        mRemoteViews.setProgressBar(R.id.progress_bar, max, progress, false);
        mRemoteViews.setTextViewText(R.id.btn_play, isPlaying ? "暂停" : "播放");

        mNotification.when = System.currentTimeMillis();
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

    private void registerViewClick(int idRes, String action) {
        Intent intent = new Intent(action);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(mPlayerService, 0, intent, 0);
        mRemoteViews.setOnClickPendingIntent(idRes, pendingIntent);
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            LogUtil.i("onReceive, action: " + intent.getAction());
            switch (intent.getAction()) {
                case ACTION_PRE:
                    mMediaController.getTransportControls().skipToPrevious();
                    break;
                case ACTION_PLAY:
                    if (mPlayerService.isPlaying()) {
                        mMediaController.getTransportControls().pause();
                    } else {
                        mMediaController.getTransportControls().play();
                    }
                    break;
                case ACTION_NEXT:
                    mMediaController.getTransportControls().skipToNext();
                    break;
                case ACTION_TYPE:
                    mMediaController.getTransportControls().sendCustomAction(ACTION_LOOP_TYPE, null);
                    break;
            }
        }
    };
}
